/**
 * 字段验证器模块
 * 提供可配置的数据验证策略
 */

const util = require('../../../framework/helpers/util.js');

/**
 * 验证规则定义
 * 每个规则包含验证逻辑和错误消息
 */
const VALIDATION_RULES = {
  // 非空验证
  required: {
    validate: (value) => value !== null && value !== undefined && value !== '',
    message: (fieldName) => `${fieldName}不能为空`
  },
  
  // 最小长度验证
  minLength: {
    validate: (value, length) => !value || String(value).length >= length,
    message: (fieldName, length) => `${fieldName}长度不能小于${length}个字符`
  },
  
  // 最大长度验证
  maxLength: {
    validate: (value, length) => !value || String(value).length <= length,
    message: (fieldName, length) => `${fieldName}长度不能超过${length}个字符`
  },
  
  // 数字验证
  isNumber: {
    validate: (value) => !value || (!isNaN(Number(value)) && isFinite(value)),
    message: (fieldName) => `${fieldName}必须是数字`
  },
  
  // 整数验证
  isInteger: {
    validate: (value) => !value || (Number.isInteger(Number(value))),
    message: (fieldName) => `${fieldName}必须是整数`
  },
  
  // 最小值验证
  min: {
    validate: (value, min) => !value || Number(value) >= min,
    message: (fieldName, min) => `${fieldName}不能小于${min}`
  },
  
  // 最大值验证
  max: {
    validate: (value, max) => !value || Number(value) <= max,
    message: (fieldName, max) => `${fieldName}不能大于${max}`
  },
  
  // 邮箱格式验证
  isEmail: {
    validate: (value) => {
      if (!value) return true;
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      return emailRegex.test(value);
    },
    message: (fieldName) => `${fieldName}格式不正确`
  },
  
  // 日期验证
  isDate: {
    validate: (value) => {
      if (!value) return true;
      const date = new Date(value);
      return !isNaN(date.getTime());
    },
    message: (fieldName) => `${fieldName}必须是有效的日期`
  },
  
  // 正则表达式验证
  pattern: {
    validate: (value, pattern) => {
      if (!value) return true;
      const regex = new RegExp(pattern);
      return regex.test(String(value));
    },
    message: (fieldName) => `${fieldName}格式不正确`
  }
};

/**
 * 项目字段验证配置
 * 为每个字段配置适用的验证规则
 */
const PROJECT_FIELD_VALIDATIONS = {
  // 基础字段验证
  model: [
    { rule: 'required' },
    { rule: 'maxLength', param: 50 }
  ],
  projectType: [
    { rule: 'required' }
  ],
  customerName: [
    { rule: 'required' },
    { rule: 'maxLength', param: 100 }
  ],
  priority: [
    { rule: 'required' }
  ],
  startDate: [
    { rule: 'required' },
    { rule: 'isNumber' }
  ],
  deadline: [
    { rule: 'required' },
    { rule: 'isNumber' }
  ],
  
  // 扩展字段验证
  'extData.controlMode': [
    { rule: 'maxLength', param: 50 }
  ],
  'extData.maxSpeed': [
    { rule: 'isNumber' }
  ],
  'extData.ratedVoltage': [
    { rule: 'pattern', param: '^[0-9]+(\\.[0-9]+)?V$' }
  ]
};

/**
 * 根据字段名获取验证规则
 * @param {string} fieldName 字段名
 * @returns {Array} 验证规则数组
 */
function getFieldValidations(fieldName) {
  return PROJECT_FIELD_VALIDATIONS[fieldName] || [];
}

/**
 * 验证单个字段
 * @param {string} fieldName 字段名
 * @param {*} value 字段值
 * @param {Object} data 完整数据对象
 * @returns {Object} 验证结果 {valid, message}
 */
function validateField(fieldName, value, data = {}) {
  const validations = getFieldValidations(fieldName);
  
  for (const validation of validations) {
    const rule = VALIDATION_RULES[validation.rule];
    
    if (!rule) {
      console.warn(`[FieldValidator] 未知的验证规则: ${validation.rule}`);
      continue;
    }
    
    const isValid = rule.validate(value, validation.param);
    if (!isValid) {
      // 获取显示名称
      const displayName = getFieldDisplayName(fieldName);
      
      return {
        valid: false,
        message: rule.message(displayName, validation.param)
      };
    }
  }
  
  return { valid: true };
}

/**
 * 验证数据对象
 * @param {Object} data 要验证的数据对象
 * @param {Array} fields 要验证的字段数组，为空则验证所有配置的字段
 * @returns {Object} 验证结果 {valid, errors}
 */
function validateData(data, fields = null) {
  const errors = {};
  let hasError = false;
  
  // 确定要验证的字段
  const fieldsToValidate = fields || Object.keys(PROJECT_FIELD_VALIDATIONS);
  
  // 验证每个字段
  for (const fieldName of fieldsToValidate) {
    // 处理扩展字段路径（如extData.field）
    let value;
    if (fieldName.startsWith('extData.')) {
      const extField = fieldName.replace('extData.', '');
      value = data.extData && data.extData[extField];
    } else {
      value = data[fieldName];
    }
    
    const result = validateField(fieldName, value, data);
    if (!result.valid) {
      errors[fieldName] = result.message;
      hasError = true;
    }
  }
  
  return {
    valid: !hasError,
    errors: errors
  };
}

/**
 * 获取字段显示名称
 * @param {string} fieldName 字段名
 * @returns {string} 显示名称
 */
function getFieldDisplayName(fieldName) {
  const displayNames = {
    'model': '项目型号',
    'projectType': '项目类型',
    'customerName': '客户名称',
    'priority': '优先级',
    'startDate': '开始日期',
    'deadline': '截止日期',
    'extData.controlMode': '控制模式',
    'extData.maxSpeed': '最大转速',
    'extData.ratedVoltage': '额定电压'
  };
  
  // 移除extData前缀
  const simpleName = fieldName.replace('extData.', '');
  
  return displayNames[fieldName] || displayNames[simpleName] || fieldName;
}

/**
 * 根据项目类型获取需要验证的字段
 * @param {string} projectType 项目类型
 * @returns {Array} 字段名数组
 */
function getFieldsByProjectType(projectType) {
  // 基础字段，所有项目类型都需要验证
  const baseFields = [
    'model', 'projectType', 'customerName', 'priority', 
    'startDate', 'deadline'
  ];
  
  // 根据项目类型添加特有字段
  let typeSpecificFields = [];
  
  if (projectType === '霍尔' || projectType === '磁编') {
    typeSpecificFields = [
      'extData.controlMode', 
      'extData.controlAlgorithm',
      'extData.controlInterface'
    ];
  } else if (projectType === '风机') {
    typeSpecificFields = [
      'extData.fanType',
      'extData.airFlow',
      'extData.staticPressure'
    ];
  } else if (projectType === '水泵') {
    typeSpecificFields = [
      'extData.pumpType',
      'extData.flowRate',
      'extData.headHeight'
    ];
  }
  
  return [...baseFields, ...typeSpecificFields];
}

module.exports = {
  validateField,
  validateData,
  getFieldsByProjectType,
  PROJECT_FIELD_VALIDATIONS
}; 